﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace WebRole1
{
    public partial class login : System.Web.UI.Page
    {
        dbManager db = new dbManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
        }

      


        protected void Button1_Click(object sender, EventArgs e)
        {
            UserClass user = new UserClass();
            string email = TextBox1.Text;
            string password = TextBox2.Text;
            user = db.login(email, password);
            if (user == null)
            {
                Label1.Visible = true;
            }
            else
            {
                Label1.Visible = false;
                Session["user"] = user;
                bool isAdmin = false;
                try
                {
                    foreach (String s in user.Roles)
                    {
                        if (s.Equals("admin"))
                        {
                            isAdmin = true;
                        }
                    }
                }
                catch (Exception) { }

                string type = "user";
                if (isAdmin == true)
                {
                    type = "admin";
                }
                Session["isAdmin"] = isAdmin;
                // create a form authentication ticket
                FormsAuthenticationTicket tkt;
                string cookiestr;
                HttpCookie ck;
                tkt = new FormsAuthenticationTicket(1, user.Name, DateTime.Now,
          DateTime.Now.AddMinutes(30), false, type);
                cookiestr = FormsAuthentication.Encrypt(tkt);
                ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);
                Response.Redirect("default.aspx");
            }
        }
    }
}